package com.kbbywyclient.ui.fragment;

import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kbbywyclient.R;
import com.kbbywyclient.app.Constants;
import com.kbbywyclient.data.entity.IncomeRecordData;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.RecommendRecordModule;
import com.kbbywyclient.presenter.IncomeRecordPresenter;
import com.kbbywyclient.ui.adapter.base.BaseAdapter;
import com.kbbywyclient.ui.contarct.IncomeRecordContract;
import com.kbbywyclient.ui.fragment.base.BaseFragment;
import com.kbbywyclient.ui.pop.PureListPop;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.widget.divider.VerticalItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Jiangzx on 2017/10/31 17:40.
 * 收入记录
 */

public class IncomeRecordFragment extends BaseFragment implements IncomeRecordContract.View{
    @BindView(R.id.app_bar)
    AppBarLayout appBar;

    @BindView(R.id.rl_bank_type)
    RelativeLayout rlBankType;
    @BindView(R.id.tv_bank)
    TextView tvBank;
    @BindView(R.id.sr_layout)
    SmartRefreshLayout srLayout;
    @BindView(R.id.recycle_view)
    RecyclerView recyclerView;

    @BindView(R.id.tv_total_income)
    TextView tvTotalReward;

    private PureListPop<IncomeRecordData.Bank> pop;

    @Inject
    IncomeRecordPresenter presenter;

    private BaseAdapter<IncomeRecordData.Record> adapter;
    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_income_record;
    }

    @Override
    protected void initView() {
        srLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                presenter.mPage++;
                presenter.loadRecords(getUser().getSalesID(),
                        presenter.mBankId,
                        presenter.mPage);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                presenter.clearList();
                if(adapter!=null){
                    adapter.notifyDataSetChanged();
                }
                presenter.loadRecords(getUser().getSalesID(),
                        presenter.mBankId,
                        presenter.mPage);
            }
        });
        final LinearLayoutManager layoutManager=
                new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(layoutManager);
        VerticalItemDecoration decoration=new VerticalItemDecoration(Constants.DIVIDER_COLOR,1);
        int padding=getResources().getDimensionPixelSize(R.dimen.margin_15dp);
        decoration.setPaddingLeftRight(padding,padding);
        recyclerView.addItemDecoration(decoration);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&
                        layoutManager.findFirstCompletelyVisibleItemPosition()==0){
                    appBar.setExpanded(true,true);
                }
            }
        });

        tvBank.setText("不限");
        tvTotalReward.setText("以下可获收入：--");
    }

    @Override
    protected void initData() {
        srLayout.autoRefresh();
    }

    @Override
    protected void initAppComponent(AppComponent appComponent) {
        appComponent.getRecommendRecordComponent(new RecommendRecordModule(this)).inject(this);
    }

    @OnClick(R.id.rl_bank_type)
    public void onClick(View view){
        switch (view.getId()){
            case R.id.rl_bank_type:
                showFilterPop();
                break;
        }
    }

    private void showFilterPop(){
        if(pop==null){
            return;
        }
        int[] position=new int[2];
        rlBankType.getLocationOnScreen(position);
        if(!pop.isShowing()){
            tvBank.setCompoundDrawablesWithIntrinsicBounds(null,
                    null,
                    ContextCompat.getDrawable(getContext(),R.mipmap.icon_green_arrow_up),
                    null);
            pop.showAtLocation(rlBankType,
                    Gravity.NO_GRAVITY,
                    position[0],
                    position[1]+rlBankType.getHeight());
        }
    }

    public void loadDataSuccess(String totalReward,List<IncomeRecordData.Bank> bankList){
        String showText;
        if(TextUtils.isEmpty(totalReward)){
            showText="以下可获收入：￥0.00";
        }else{
            showText="以下可获收入：￥"+totalReward;
        }
        SpannableStringBuilder builder=new SpannableStringBuilder(showText);
        int start=showText.indexOf("￥");
        int end=showText.length();
        builder.setSpan(new ForegroundColorSpan(0XFF1ACBB4),
                start,end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        builder.setSpan(new RelativeSizeSpan(1.28f),
                start,end,Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvTotalReward.setText(builder);
        if(pop==null){
            List<IncomeRecordData.Bank> popList=new ArrayList<>();
            popList.add(new IncomeRecordData.Bank(-1,"不限"));
            if(bankList!=null&&bankList.size()>0){
                popList.addAll(bankList);
            }
            pop=new PureListPop<>(getContext(), popList, bank -> {
                if(bank.getCompany_id()!=presenter.mBankId){
                    presenter.mBankId=bank.getCompany_id();
                    tvBank.setText(bank.getBankName());
                    srLayout.autoRefresh();
                }
                pop.dismiss();
            });
            pop.setOnDismissListener(() -> tvBank.setCompoundDrawablesWithIntrinsicBounds(
                    null,
                    null,
                    ContextCompat.getDrawable(getContext(),R.mipmap.icon_green_arrow_down),
                    null));
            pop.setWidth(rlBankType.getWidth());
            pop.setHeight((int) (StringUtil.getScreenHeight()*0.45f));
        }
    }

    @Override
    public void loadRecordsSuccess(List<IncomeRecordData.Record> data, boolean canLoadMore) {
        if(adapter==null){
            adapter=new BaseAdapter<IncomeRecordData.Record>(data,R.layout.item_recommend_record) {
                @Override
                public void convert(Holder holder, IncomeRecordData.Record item, int position) {
                    holder.setText(R.id.tv_bank,item.getNameShort());
                    holder.setText(R.id.tv_rec_count,item.getNum()+"人");
                    holder.setText(R.id.tv_money,"￥"+item.getPrize_amount());
                    holder.setText(R.id.tv_date,item.getCreate_time());
                }
            };
            recyclerView.setAdapter(adapter);
        }else{
            adapter.notifyDataSetChanged();
        }
        srLayout.setLoadmoreFinished(!canLoadMore);
    }

    @Override
    public void loadRecordsComplete() {
        srLayout.finishRefresh();
        srLayout.finishLoadmore();
    }
}
